using System;

namespace Microsoft.Phone.Reactive
{
    /// <summary>
    /// Repeatable task.
    /// </summary>
    public class RepeatableTask : DisposableTaskBase
    {
        /// <summary>
        /// Initializes new instance of class.
        /// </summary>
        /// <param name="period"></param>
        /// <param name="scheduler"></param>
        /// <param name="onNext"></param>
        /// <param name="onError"></param>
        /// <param name="onCompleted"></param>
        /// <exception cref="ArgumentNullException"></exception>
        public RepeatableTask(
            TimeSpan period,
            IScheduler scheduler,
            Action<Timestamped<long>> onNext,
            Action<Exception> onError,
            Action onCompleted = null)
            : base(scheduler)
        {
            if (onNext == null)
            {
                throw new ArgumentNullException("onNext");
            }

            if (onError == null)
            {
                throw new ArgumentNullException("onError");
            }

            var observable = Observable.Interval(period).Timestamp().SubscribeOn(Scheduler);

            Task = onCompleted == null
                       ? observable.Subscribe(onNext, onError)
                       : observable.Subscribe(onNext, onError, onCompleted);
        }
    }
}